/*
	X - Horizontal
	Y - Vertical
	
	maps: id, width, height, name, school_id
	mapPieces: pos_x, pos_y, width, height, filename
	mapLocs: id, pos_x, pos_y, name, address, isStore
	mapLocDetails: name, address, likeCount, dislikeCount, commentCount
	discounts : id, name, createTime, validTime, expireTime, smallPic, largePic
	comments : content, createTime, user.name
*/

function inside(x, y, x1, y1, x2, y2){
	return (x <= x2 && x >= x1) && (y <= y2 && y >= y1);
}

function textWidth(obj, text){
	var calc = '<span style="display:none;' + obj.attr("style") + '">' + text + '</span>';
	$('body').append(calc);
	var width = $('body').find('span:last').width();
	$('body').find('span:last').remove();
	return width;
}

var MapCtrl = dojo.declare(null, {
	//constructor/desctuctor
	constructor : mapCtrl_contructor,
	destroy : mapCtrl_destructor,
	
	//methods
	addMapLocConmment : mapCtrl_addMapLocComment,
	init : mapCtrl_init,
	loadMapLocPage : mapCtrl_loadMapLocPage,
	loadMapLocLike : mapCtrl_loadMapLocLike,
	loadMapPage : mapCtrl_loadMapPage,
	loadStoreDiscounts : mapCtrl_loadStoreDiscounts,
	showMap : mapCtrl_showMap,
	showMapLocPic : mapCtrl_showMapLocPic,
	
	//slots
	sizeChanged : mapCtrl_sizeChanged,
	updateLoginState : mapCtrl_updateLoginState
});

function mapCtrl_contructor(){
	this.mapPage = "";
	this.locPage = "";
	this.curPage = "";
	this.curMap = -1;
	this.curMapLoc = -1;
	this.curMapLocPic = -1;
	this._pageCommentCount = 10;
	this.mapLocX = 0;
	this.mapLocY = 0;
	this.maps = new Array();
	this.mapPieces = new Array();
	this.mapLocs = new Array();
	this.mapLocPics = new Array();
	this.discounts = new Array();
	this._mapLoader = null;
	this._mapLocLoader = null;
	this._parameter = {};
	this._connections = new Array();
}

function mapCtrl_destructor(){
	for (var i = 0; i < this._connections.length; i ++)
		dojo.disconnect(this._connections[i]);
	
	if (this._mapLoader != null) this._mapLoader.destroy();
	if (this._mapLocLoader != null) this._mapLocLoader.destroy();
}

function mapCtrl_addMapLocComment(){
	var obj = this;
	if (obj.locPage.find("#input_content").val().length == 0){
		globalCtrl.showPopupDialog("notify_msg", {content : "请输入评价内容。", title : "错误"});
		return;
	}
	function showCommentMsg(msg){
		obj.locPage.find("#comment_msg").html(msg);
		obj.locPage.find("#comment_msg").show();
	}
	showCommentMsg("正在发送评论...");
	obj.locPage.find("#input_content").attr("disabled", "true");
	
	$.post("/map/addSchoolMapLocComment", {id : obj.mapLocs[this.curMapLoc][0], content : obj.locPage.find("#input_content").val()}, function(data){
		if (data == "success"){
			obj.locPage.find("#input_content").val("");
			obj._commentList.update();
			showCommentMsg("评论成功！");
		}  else {
			showCommentMsg("评论发送失败。");
		}  
		obj.locPage.find("#input_content").removeAttr("disabled");
	});
}

function mapCtrl_init(parameter){
	this._connections.push(dojo.connect(globalCtrl, "userLoginStateChanged", this, "updateLoginState"));
	if (parameter != null) this._parameter = parameter;
	if (this._parameter.floater != null)
		this._connections.push(dojo.connect(this._parameter.floater, "sizeChanged", this, "sizeChanged"));
	
	var readyCount = 0;
	var obj = this;
	function checkReady(){
		readyCount ++;
		if (readyCount == 2) obj.loadMapPage(0, false);
	}
	
	this._mapLoader = new PageLoader("/homepage/getMainPage", null, {postData : {"page" : "map_map"},
		CSS : ["/css/homepage/mainpage_map_map.css", "/plugins/jquery_lightbox/css/jquery.lightbox.css"]}, {}, function(data){
			obj.mapPage = $("#page_map").html(data);
			$.getJSON("/map/getSchoolMaps", function(data){
				obj.maps = data;
				for (var i = 0; i < obj.maps.length; i ++)
					$("#page_map #toolbar #input_school").append("<option value='" + obj.maps[i][0] + "'>" + obj.maps[i][3] + "</option>");
				checkReady();
			});
	});
	this._mapLocLoader = new PageLoader("/homepage/getMainPage", null, {postData : {"page" : "map_loc"},
		CSS : ["/css/homepage/mainpage_map_loc.css"]}, {}, function(data){
			obj.locPage = $("#page_loc").html(data);
			obj.locPage.find("#comment_buttons #button_add").unbind();
			obj.locPage.find("#comment_buttons #button_add").click(function(){
				obj.addMapLocConmment();
			});
			checkReady();
	});
}

function mapCtrl_loadMapPage(id, needSlide){
	var obj = this;
	var readyCount = 0;
	if (needSlide == null) needSlide = true;
	function checkReady(){
		readyCount ++;
		if (readyCount == 2){
			obj.mapPage.find("#page_main").fadeIn();
			var frameWidth = obj.mapPage.find("#map").width();
			var frameHeight = obj.mapPage.find("#map").height();
			obj.mapPage.find("#map #map_elementlist").width(obj.maps[obj.curMap][1]);
			obj.mapPage.find("#map #map_elementlist").height(obj.maps[obj.curMap][2]);
			var mapPos = $("#map").offset();
			obj.mapPage.find("#map #map_all").draggable({"containment" : 
				[- obj.maps[obj.curMap][1] + frameWidth + mapPos.left, - obj.maps[obj.curMap][2] + frameHeight + mapPos.top, mapPos.left, mapPos.top],
				"cursor" : "move", "stop" : function(){
					obj.showMap();
				}
			});
		}
	}
	
	if (obj.curPage == "map" && obj.curMap == id) return;
	obj.mapPage.find("#page_main").hide();
	if (obj.curPage != "map"){
		if (needSlide){
			$("#page_" + obj.curPage).effect("slide", {mode : "hide", direction : "right"}, "slow");
			obj.mapPage.effect("slide", {mode : "show"}, "slow", showIt);
		}  else {
			$("#page_" + obj.curPage).hide();
			obj.mapPage.show();
			showIt();
		}  
		obj.curPage = "map";
	}  else {
		showIt();
	}
	function showIt(){
		obj.mapPage.show();
		if (obj.curMap != id){
			obj.curMap = id;
			obj.mapPage.find("#map #map_elementlist").html("");
			$.getJSON("/map/getSchoolMapPiecesByMapId", {"id" : obj.maps[id][0]}, function(data){
				obj.mapPieces = data;
				for (var i = 0; i < obj.mapPieces.length; i ++){
					obj.mapPage.find("#map #map_elementlist").append("<img class='map_piece' id='map_piece_" + i + "'></img>");
					mapPiece = obj.mapPage.find("#map #map_elementlist #map_piece_" + i);
					mapPiece.css("left", obj.mapPieces[i][0]);
					mapPiece.css("top", obj.mapPieces[i][1]);
					mapPiece.css("width", obj.mapPieces[i][2]);
					mapPiece.css("height", obj.mapPieces[i][3]);
				}
				checkReady();
				obj.showMap(obj.maps[id][1] / 2, obj.maps[id][2] / 2);
			});
			$.getJSON("/map/getSchoolMapLocsByMapId", {"id" : obj.maps[id][0]}, function(data){
				obj.mapLocs = data;
				for (var i = 0; i < obj.mapLocs.length; i ++){
					obj.mapPage.find("#map #map_elementlist").append("<div class='map_loc' href='javascript:showMapLocDetails(" + i +")' id='map_loc_" + i + "'></div>");
					mapLoc = obj.mapPage.find("#map #map_elementlist #map_loc_" + i);
					mapLoc.css("left", obj.mapLocs[i][1]);
					mapLoc.css("top", obj.mapLocs[i][2]);
					mapLoc.attr("arrayId", i);
					mapLoc.click(function(){
						var id = $(this).attr("arrayId");
						var leftWidth = textWidth($("#loc_info #store_name"), obj.mapLocs[id][3]) + 20;
						if (leftWidth < 150) leftWidth = 150;
						$("#loc_info #column_left").width(leftWidth);
						$("#loc_info #store_name").html(obj.mapLocs[id][3]);
						$("#loc_info #store_address").html(obj.mapLocs[id][4]);
						$("#loc_info #panel_detail_link").attr("arrayId", id);
						$("#loc_info #panel_detail_link").click(function(){
							var id = $("#loc_info #panel_detail_link").attr("arrayId");
							obj.loadMapLocPage(id);
						});
						$("#loc_info").css("left", obj.mapLocs[id][1] + 10);
						$("#loc_info").css("top", obj.mapLocs[id][2] + 10);
						$("#loc_info #store_pic").html("");
						$.getJSON("/map/getSchoolMapLocPics", {"id" : obj.mapLocs[id][0]}, function(data){
							for (var j = 0; j < data.length; j ++){
								if (data[j][0] == 'small'){
									$("#loc_info #store_pic").html("<img src='" + data[j][1] + "'></img>");
									break;
								}
							}
							$("#loc_info #column_left_margin").height($("#loc_info").height() - $("#loc_info #store_name").height() - 
								$("#loc_info #store_address").height() - $("#loc_info #store_panel").height());
						});
						$("#loc_info").show();
					});
				}
				checkReady();
				obj.showMap(obj.maps[id][1] / 2, obj.maps[id][2] / 2);
			});
		}  else {
			checkReady();
			checkReady();
		}  
	}
}

function mapCtrl_loadMapLocPage(id){
	var obj = this;
	if (obj.curPage == "loc" && obj.curMapLoc == id) return;
	var readyCount = 0;
	obj.locPage.find("#page_main").hide();
	if (obj.curPage != "loc"){
		$("#page_" + obj.curPage).effect("slide", {mode : "hide", direction : "right"}, "slow");
		obj.locPage.effect("slide", {mode : "show"}, "slow", showIt);
		obj.curPage = "loc";
	}  else {
		showIt();
	}
	function checkReady(){
		readyCount ++;
		if (readyCount == 2){
			obj.showMapLocPic(0);
			obj.locPage.find("#page_main").fadeIn();
		}
	}
	function showIt(){
		obj.locPage.find("#input_content").removeAttr("disabled");
		obj.locPage.find("#comment_msg").hide();
		obj.locPage.show();
		obj.curMapLocPic = -1;
		if (obj.curMapLoc != id){
			obj.curMapLoc = id;
			obj.locPage.find("#toolbar #button_return").click(function(){
				obj.loadMapPage(obj.curMap);
			});
			obj.locPage.find("#locinfo #loc_name").html(obj.mapLocs[id][3]);
			obj.locPage.find("#locinfo #loc_address").html(obj.mapLocs[id][4]);
			$.getJSON("/map/getSchoolMapLocDetails", {"id" : obj.mapLocs[id][0]}, function(data){
				obj.locPage.find("#locinfo #loc_like_public").html(data[0][2] + "人喜欢这个地点<br>" + data[0][3] + "人讨厌这个地点");
				obj.locPage.find("#locinfo #loc_comment_count").html(data[0][4] + "条评论");
				checkReady();
			});
			$.getJSON("/map/getSchoolMapLocPics", {"id" : obj.mapLocs[id][0]}, function(data){
				$("#page_loc #locinfo #gallery").html("");
				var imgHtml = $("#page_loc #locinfo #gallery_item_example").html();
				obj.mapLocPics = new Array();
				for (var i = 0; i < data.length; i ++){
					if (data[i][0] == "large"){
						obj.locPage.find("#locinfo #gallery").append("<div id='gallery_img_" + obj.mapLocPics.length + "'>" + imgHtml + "</div>");
						obj.locPage.find("#locinfo #gallery_img_" + obj.mapLocPics.length + " img").attr("src", data[i][1]);
						obj.mapLocPics.push(data[i]);
					}
				}
				checkReady();
			});
			
			obj._commentList = new TabList();
			obj._commentList.init({baseItem : obj.locPage.find("#comment_list"), listName : "评论", defaultTab : 0, 
				tabHidden : true,
				contentAppending : true,
				tabs : [["全部", "/map/getSchoolMapLocComments", {"id" : obj.mapLocs[obj.curMapLoc][0]}, "/map/getSchoolMapLocCommentCount", {"id" : obj.mapLocs[obj.curMapLoc][0]}]],
				itemHtml : obj.locPage.find("#comment_item_example").html(),
				itemHtmlMapping : [[0, "comment_content", "text"], [1, "comment_date", "text"], [2, "comment_user", "text"]]});
			
			obj.loadMapLocLike();
			if (obj.mapLocs[obj.curMapLoc][5] == 1) obj.loadStoreDiscounts();
			else obj.locPage.find("#discounts").hide();
			obj.locPage.show();
		}  else {
			checkReady();
			checkReady();
		}  
	}
}

function mapCtrl_loadMapLocLike(){
	var obj = this;
	if (obj.curPage != "loc") return;
	obj.locPage.find("#locinfo #user_post_like").unbind();
	obj.locPage.find("#locinfo #user_post_like").click(function(){
		$.post("/map/setSchoolMapLocUserLike", {"id" : obj.mapLocs[obj.curMapLoc][0], "type" : "like"}, function(data){
			obj.loadMapLocLike();
		});
	});
	obj.locPage.find("#locinfo #user_post_dislike").unbind();
	obj.locPage.find("#locinfo #user_post_dislike").click(function(){
		$.post("/map/setSchoolMapLocUserLike", {"id" : obj.mapLocs[obj.curMapLoc][0], "type" : "dislike"}, function(data){
			obj.loadMapLocLike();
		});
	});
	obj.locPage.find("#locinfo #loc_like_user_status").html("正在载入个人评价...");
	obj.locPage.find("#locinfo #loc_like_user_post").hide();
	obj.locPage.find("#locinfo #loc_like_user_status").show();
	$.post("/map/getSchoolMapLocUserLike", {"id" : obj.mapLocs[obj.curMapLoc][0]}, function(data){
		if (data == "notLoggedIn"){
			obj.locPage.find("#locinfo #loc_like_user_status").html("登录后评价此地点...");
			obj.locPage.find("#locinfo #loc_like_user_post").hide();
			obj.locPage.find("#locinfo #loc_like_user_status").show();
		}  else if (data == "error"){
			obj.locPage.find("#locinfo #loc_like_user_status").html("错误。");
			obj.locPage.find("#locinfo #loc_like_user_post").hide();
			obj.locPage.find("#locinfo #loc_like_user_status").show();
		}  else if (data == "like"){
			obj.locPage.find("#locinfo #loc_like_user_status").html("这是我喜欢的地点！");
			obj.locPage.find("#locinfo #loc_like_user_post").hide();
			obj.locPage.find("#locinfo #loc_like_user_status").show();
		}  else if (data == "dislike"){
			obj.locPage.find("#locinfo #loc_like_user_status").html("这是我讨厌的地点！");
			obj.locPage.find("#locinfo #loc_like_user_post").hide();
			obj.locPage.find("#locinfo #loc_like_user_status").show();
		}  else {
			obj.locPage.find("#locinfo #loc_like_user_post").show();
			obj.locPage.find("#locinfo #loc_like_user_status").hide();
		}
	});
}

function mapCtrl_loadStoreDiscounts(){
	var obj = this;
	if (obj.curPage != "loc") return;
	$.getJSON("/map/getDiscountByStoreId", {"id" : obj.mapLocs[obj.curMapLoc][0]}, function(data){
		obj.discounts = data;
		obj.locPage.find("#discounts #discount_list").html("");
		var itemHtml = obj.locPage.find("#discounts #discount_item_example").html();
		for (var i = 0; i < obj.discounts.length; i ++){
			obj.locPage.find("#discounts #discount_list").append("<div id='discount_item_" + i + "'>" + itemHtml + "</div>");
			var item = obj.locPage.find("#discounts #discount_item_" + i);
			item.find("#discount_item_name").html(obj.discounts[i][1]);
			item.find("#discount_item_validtime").html("生效时间：" + obj.discounts[i][3]);
			item.find("#discount_item_expiretime").html("有效期至：" + obj.discounts[i][4]);
			item.find("a").attr("href", obj.discounts[i][6]);
			item.find("img").attr("src", obj.discounts[i][5]);
			obj.locPage.find("#discounts #discount_list #discount_item_link").lightBox();
		}
		obj.locPage.find("#discounts").show();
	});
}

function mapCtrl_showMap(x, y){
	var obj = this;
	if (obj.curPage != "map") return;
	var frameWidth = obj.mapPage.find("#map").width();
	var frameHeight = obj.mapPage.find("#map").height();
	if (x == null || y == null){
		obj.mapLocX = frameWidth / 2 - obj.mapPage.find("#map #map_all").position().left;
		obj.mapLocY = frameHeight / 2 - obj.mapPage.find("#map #map_all").position().top;
	}  else {
		obj.mapLocX = x;
		obj.mapLocY = y;
	}
	var minX = obj.mapLocX - frameWidth / 2, minY = obj.mapLocY - frameHeight / 2;
	var maxX = obj.mapLocX + frameWidth / 2, maxY = obj.mapLocY + frameHeight / 2;
	obj.mapPage.find("#map #map_all").css("left", (- minX));
	obj.mapPage.find("#map #map_all").css("top", (- minY));
	for (var i = 0; i < obj.mapPieces.length; i ++){
		var x1 = obj.mapPieces[i][0], x2 = obj.mapPieces[i][0] + obj.mapPieces[i][2];
		var y1 = obj.mapPieces[i][1], y2 = obj.mapPieces[i][1] + obj.mapPieces[i][3];
		if (inside(x1, y1, minX, maxX, minY, maxY) || inside(x2, y2, minX, maxX, minY, maxY) || 
			inside(minX, minY, x1, y1, x2, y2) || (minY <= y2 && minY >= y1 && x1 <= maxX && x1 >= minX) ||
			(minX <= x2 && minX >= x1 && y1 <= maxY && y1 >= minY)){
				obj.mapPage.find("#map #map_piece_" + i).attr("src", obj.mapPieces[i][4]);
		}
	}
}

function mapCtrl_showMapLocPic(id){
	var obj = this;
	if (obj.curPage != "loc" || obj.curMapLocPic == id) return;
	obj.locPage.find("#locinfo #gallery_img_" + obj.curMapLocPic).hide();
	obj.locPage.find("#locinfo #gallery_img_" + id).show();
	obj.curMapLocPic = id;
}

function mapCtrl_sizeChanged(){
	var obj = this;
	if (obj.curPage == "map"){
		obj.mapPage.find("#page_main").fadeIn();
		var frameWidth = obj.mapPage.find("#map").width();
		var frameHeight = obj.mapPage.find("#map").height();
		obj.mapPage.find("#map #map_elementlist").width(obj.maps[obj.curMap][1]);
		obj.mapPage.find("#map #map_elementlist").height(obj.maps[obj.curMap][2]);
		var mapPos = $("#map").offset();
		obj.mapPage.find("#map #map_all").draggable({"containment" : 
			[- obj.maps[obj.curMap][1] + frameWidth + mapPos.left, - obj.maps[obj.curMap][2] + frameHeight + mapPos.top, mapPos.left, mapPos.top],
			"cursor" : "move"	
		});
		
		obj.showMap(obj.mapLocX, obj.mapLocY);
	}
}

function mapCtrl_updateLoginState(){
	this.loadMapLocLike();
}

if (dojo.getObject("mapCtrl") == null) mapCtrl = new MapCtrl();